//
//  MapViewController.m
//  Findif
//
//  Created by Mac on 2018/12/18.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "MapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <MapKit/MapKit.h>
#import "JZLocationConverter.h"

@interface MapViewController ()<MAMapViewDelegate>

@property (nonatomic, strong)MAMapView * mapView;
@property (nonatomic, strong)AMapLocationManager *locationManager;
@property (nonatomic, weak)UIButton * showUserLocalButton;
@property (nonatomic, weak)UIView * whiteView;
@property (nonatomic, weak)UILabel * titleLabel;
@property (nonatomic, weak)UILabel * localLabel;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, weak)UIButton * button;


@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.view.backgroundColor = ZRWhiteColor;
    self.title = @"地图导航";
    
[self setupUI];
}

- (void)setupUI {
    
    ///初始化地图
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.showsUserLocation = YES;
    self.mapView.delegate = self;
    self.mapView.showsCompass = NO;
    self.mapView.showsScale = NO;
    [self.mapView setZoomLevel:14 animated:YES];
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    ///把地图添加至view
    [self.view addSubview:self.mapView];
    
    //    self.locationManager = [[AMapLocationManager alloc] init];
    //    self.locationManager.delegate = self;
    //    [self.locationManager startUpdatingLocation];
    //
    //    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];    // 带逆地理信息的一次定位（返回坐标和地址信息）
    //    self.locationManager.locationTimeout =2;    //   定位超时时间，最低2s，此处设置为2s
    //    self.locationManager.reGeocodeTimeout = 2;
    
    double latitude = [self.merchants_latitude doubleValue];
    double longitude = [self.merchants_longitude doubleValue];
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(latitude, longitude)];
    [self addAnnotationwith:0 WithCoordinate:CLLocationCoordinate2DMake(latitude, longitude)];
    
    UIButton * showUserLocalButton = [UIButton new];
    
    [showUserLocalButton setImage:[UIImage imageNamed:@"回到位置"] forState:UIControlStateNormal];
    [showUserLocalButton addTarget:self action:@selector(clickShowUserLocalButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.showUserLocalButton = showUserLocalButton;
    
    [self.view addSubview:self.showUserLocalButton];
    
    UIView * whiteView = [UIView new];
    
    whiteView.backgroundColor = ZRWhiteColor;
    whiteView.userInteractionEnabled = YES;
//    whiteView.image = [UIImage imageNamed:@"圆角矩形5"];
    
    self.whiteView = whiteView;
    
    [self.view addSubview:self.whiteView];
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.textColor = ZRBlackColor;
    if (self.merchants_name) {
        
        titleLabel.text = self.merchants_name;
    }
    
    titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    titleLabel.numberOfLines = 0;
    
    self.titleLabel = titleLabel;
    
    [self.whiteView addSubview:self.titleLabel];
    
    UILabel * localLabel = [UILabel new];
    
    localLabel.textColor = [UIColor lightGrayColor];
    localLabel.text = self.merchants_local;
    localLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    localLabel.numberOfLines = 0;
    
    self.localLabel = localLabel;
    
    [self.whiteView addSubview:self.localLabel];
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    self.lineView = lineView;
    
    [self.whiteView addSubview:self.lineView];
    
    UIButton * button = [UIButton new];
    
    [button setTitle:@"查看导航" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickNavButton) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:ColorWithRGB(0x35d499) forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.button = button;
    
    [self.whiteView addSubview:self.button];
}

/* 实现代理方法：*/
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]){
        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:userLocationStyleReuseIndetifier];
        }
        
        annotationView.image = [UIImage imageNamed:@"我的位置"];
        
        return annotationView;
        //([annotation isKindOfClass:[MAPointAnnotation class]])
    }else{
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation                                                 reuseIdentifier:pointReuseIndetifier];
        }
        annotationView.canShowCallout = NO;
        annotationView.animatesDrop = YES;
        annotationView.draggable = YES;
        annotationView.image = [UIImage imageNamed:@"导航坐标"];
        annotationView.rightCalloutAccessoryView  = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        
        
        
        return annotationView;
    }
}


//- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
//
//    if (self.currentLocation == nil) {
//
//        self.currentLocation = userLocation.location;
//    }
//}

- (void)addAnnotationwith:(NSInteger)index WithCoordinate:(CLLocationCoordinate2D)coordinate {
    
    MAPointAnnotation * a = [[MAPointAnnotation alloc] init];
    
    a.coordinate = coordinate;
    
    [self.mapView addAnnotation:a];
    
}

- (void)clickNavButton{
    
    NSString *urlScheme = @"MapJump://";
    NSString *appName = @"Findif";
    double latitude = [self.merchants_latitude doubleValue];
    double longitude = [self.merchants_longitude doubleValue];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);//要导航的终点的经纬度
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择地图" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //这个判断其实是不需要的
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]]) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            CLLocationCoordinate2D desCoordinate = coordinate;
            
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:desCoordinate addressDictionary:nil]];
            toLocation.name = self.merchants_name;//可传入目标地点名称
            [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                           launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
        }];
        
        [alert addAction:action];
    }
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {

        CLLocationCoordinate2D desCoordinate = [JZLocationConverter gcj02ToBd09:coordinate];//火星坐标转化为百度坐标

        UIAlertAction *action = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

            //我的位置代表起点位置为当前位置，也可以输入其他位置作为起点位置，如天安门
            NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=%f,%f&mode=driving&src=JumpMapDemo", desCoordinate.latitude, desCoordinate.longitude];

            NSString *encoded = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//            NSLog(@"%@",urlString);

            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encoded]];

        }];

        [alert addAction:action];
    }
    
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        //coordinate = CLLocationCoordinate2DMake(40.057023, 116.307852);
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            CLLocationCoordinate2D desCoordinate = coordinate;
            
            NSString *urlString = [NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&sname=%@&did=BGVIS2&dname=%@&dlat=%f&dlon=%f&dev=0&m=0&t=0",@"我的位置",self.merchants_name,desCoordinate.latitude, desCoordinate.longitude];//@"我的位置"可替换为@"终点名称"
            NSString *encoded = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encoded]];
            
        }];
        
        [alert addAction:action];
    }
    
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"谷歌地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            CLLocationCoordinate2D desCoordinate = coordinate;
            
            NSString *urlString = [NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",appName,urlScheme,desCoordinate.latitude, desCoordinate.longitude];
            
            NSString *encoded = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encoded]];
            
        }];
        
        [alert addAction:action];
    }
    
    
    if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]])    {
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"腾讯地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            CLLocationCoordinate2D desCoordinate = coordinate;
            
            NSString *urlString = [NSString stringWithFormat:@"qqmap://map/routeplan?type=drive&from=我的位置&to=%@&tocoord=%f,%f&policy=1&referer=%@",self.merchants_name,desCoordinate.latitude, desCoordinate.longitude, appName];
            
           NSString *encoded = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encoded]];
            
        }];
        
        [alert addAction:action];
    }
    
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        
        alert.popoverPresentationController.sourceView = self.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(10 * SCREENH6,kScreenH - 150 * SCREENH6,355 * SCREENH6,150 * SCREENH6);
        //            self.alertVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}


- (void)clickShowUserLocalButton{
    
    self.mapView.centerCoordinate = self.mapView.userLocation.coordinate;
}


- (void)viewDidLayoutSubviews{
    
    [self.whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(84 * SCREENH6);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.mas_equalTo(self.whiteView);
//        make.height.mas_equalTo(70 * SCREENH6);
        make.width.mas_equalTo(1 * SCREENH6);
        make.trailing.mas_equalTo(self.whiteView).offset(-88 * SCREENH6);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.whiteView).offset(19 * SCREENH6);
        make.leading.mas_equalTo(self.whiteView).offset(10 * SCREENH6);
        make.trailing.mas_equalTo(self.lineView.mas_leading).offset(-5 * SCREENH6);
    }];
    
    [self.localLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.titleLabel);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.bottom.mas_equalTo(self.whiteView);
        make.top.mas_equalTo(self.lineView);
        make.leading.mas_equalTo(self.lineView.mas_trailing);
    }];
    
    [self.showUserLocalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(10 * SCREENH6);
        make.bottom.mas_equalTo(self.whiteView.mas_top).offset(-5 * SCREENH6);
        make.width.height.mas_equalTo(40 * SCREENH6);
    }];
}


@end
